<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\ding;

use app\api\service\User as UserService;
use app\common\model\ding\ClerkMember as ClerkMemberModel;
use app\common\service\message\ding\Sleep as SleepService;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 客户
 * Class UserAddress
 * @package app\common\model
 */
class ClerkMember extends ClerkMemberModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',
        'create_time',

    ];
    /*
         *睡眠客户
    */
    public function sleepUser($params)
    {

        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')
            ->where('user_id', $user['user_id'])
            ->where('shop_id', $params['shopId'])
            ->find();
        $where[] = ['shop_id', '=', $params['shopId']];
        $where[] = ['is_delete', '=', 0];

        if ($clerk['role_id'] == 2 || $clerk['role_id'] == 3) {
            $where[]  = ['clerk_id', '=', 0];
            $filter[] = ['clerk_id', '=', 0];
        } else {
            $filter[] = ['clerk_id', '=', $clerk['clerk_id']];
            $where[]  = ['clerk_id', '=', $clerk['clerk_id']];
        }
        //打盹
        $end_time   = time() - 86400 * 7;
        $start_time = time() - 86400 * 15;
        $filter[]   = ['update_time', '>', $start_time];
        $filter[]   = ['update_time', '<=', $end_time];

        $data['sleep_num1'] = $this->where($filter)->where($where)->count();

        //浅睡
        $filter             = [];
        $end_time           = time() - 86400 * 15;
        $start_time         = time() - 86400 * 30;
        $filter[]           = ['update_time', '>', $start_time];
        $filter[]           = ['update_time', '<=', $end_time];
        $data['sleep_num2'] = $this->where($filter)->where($where)->count();

        //沉睡
        $filter   = [];
        $end_time = time() - 86400 * 30;

        $filter[] = ['update_time', '<=', $end_time];

        $data['sleep_num3'] = $this->where($filter)->where($where)->count();
        $data['total']      = $data['sleep_num1'] + $data['sleep_num2'] + $data['sleep_num3'];

        $data['shop_total'] = $this->where($where)->count();
        return $data;
    }
    /*
         *睡眠客户-发送短信
    */
    public function sleepSend($type = 0)
    {

        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')
            ->where('user_id', $user['user_id'])
            ->find();
        if ($type == 1) {
            //打盹
            $end_time   = time() - 86400 * 7;
            $start_time = time() - 86400 * 15;
            $filter[]   = ['update_time', '>', $start_time];
            $filter[]   = ['update_time', '<=', $end_time];
            $users      = $this->where($filter)->where('shop_id', $clerk['shop_id'])
                ->where('clerk_id', $clerk['clerk_id'])->group('mobile')->select()->toArray();
        }
        if ($type == 2) {
            //浅睡
            $filter     = [];
            $end_time   = time() - 86400 * 15;
            $start_time = time() - 86400 * 30;
            $filter[]   = ['update_time', '>', $start_time];
            $filter[]   = ['update_time', '<=', $end_time];
            $users      = $this->where($filter)->where('shop_id', $clerk['shop_id'])->where('clerk_id', $clerk['clerk_id'])->group('mobile')->select()->toArray();
        }
        if ($type == 3) {
            //沉睡
            $filter   = [];
            $end_time = time() - 86400 * 30;

            $filter[] = ['update_time', '<=', $end_time];

            $users = $this->where($filter)->where('shop_id', $clerk['shop_id'])->where('clerk_id', $clerk['clerk_id'])->group('mobile')->select()->toArray();
        }
        if ($type == 4) {

            $users = $this->where('clerk_id', $clerk['clerk_id'])->where('shop_id', $clerk['shop_id'])
                ->group('mobile')->select()->toArray();

            //$mobiles = array_column($users, 'mobile');

        }

        foreach ($users as $key => $value) {
            $time               = time() - strtotime($value['update_time']);
            $users[$key]['day'] = round($time / 86400) + 1;
        }
        $messageService = new SleepService(self::$storeId);
        $data['users']  = $users;
        $data['clerk']  = $clerk;

        $messageService->send($data);
        return true;
    }
    public function searchUser($params)
    {

        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('user_id', $user['user_id'])
            ->field('clerk_id,shop_id')->find();

        $info = $this->where('shop_id', $clerk['shop_id'])->where('mobile', $params['keyword'])->find();
        if ($info) {
            $info['times'] = Db::name('ding_order')
                ->where('mobile', $params['keyword'])->where('shop_id', $clerk['shop_id'])->count();
        }

        return $info;
    }
    //排行榜
    public function rankUser()
    {
        $user  = UserService::getCurrentLoginUser(true);
        $clerk = Db::name('store_shop_clerk')->where('user_id', $user['user_id'])
            ->field('clerk_id,shop_id')->find();

        $lists = $this->where('status', 1)->where('shop_id', $clerk['shop_id'])->group('mobile')->limit(50)->select()->toArray();

        foreach ($lists as $key => $order) {
            $lists[$key]['times'] = Db::name('ding_order')->where('shop_id', $clerk['shop_id'])
                ->where('mobile', $order['mobile'])->where('mobile', '<>', '')->count();

        }

        // 根据 'price' 键的值对数组进行降序排序
        foreach ($lists as $key => $value) {
            $price[$key] = $value['times'];
        }

        arsort($price);

        // 重新构造数组，保持 'item' 和 'price' 的关系
        $sortedArray = [];
        foreach ($price as $key => $value) {
            $sortedArray[] = $lists[$key];
        }

        return $sortedArray;
    }

    public function getListHistory($userId = 0, $mobile = '', int $shopId = 0)
    {
        $user = UserService::getCurrentLoginUser(true);
        // 整理查询参数

        $clerk = Db::name('store_shop_clerk')
            ->where('user_id', $user['user_id'])
            ->where('shop_id', $shopId)
            ->find();

        // 检索查询条件
        $filter   = [];
        $filter[] = ['shop_id', '=', $shopId];
        if ($userId == 0) {

            $filter[] = ['mobile', '=', $mobile];

            $list = Db::name('ding_order')
                ->where($filter)
                ->order(['create_time' => 'desc'])
                ->select()->toArray();
        } else {

            // 获取列表数据
            $list = Db::name('ding_order')
                ->where($filter)
                ->where('mobile', '=', $mobile)
                ->whereOr('user_id', '=', $userId)
                ->order(['create_time' => 'desc'])
                ->select()->toArray();
        }
        foreach ($list as $key => $item) {

            $list[$key]['is_my'] = $item['clerk_id'] == $clerk['clerk_id'] ? 1 : 0;

        }

        return $list;
    }

    public function getList($param, int $limit = 15)
    {
        $user = UserService::getCurrentLoginUser(true);
        // 整理查询参数

        $params = $this->setQueryDefaultValue($param, [
            'dataType'  => 'all', // 列表模式 (全部:all 出售中:on_sale 已下架:off_sale 已售罄:sold_out)
            'status'    => -1,
            'role'      => -1,
            'shopId'    => -1,
            'searchKey' => '',
        ]);
        $clerk = Db::name('store_shop_clerk')
            ->where('user_id', $user['user_id'])
            ->where('shop_id', $params['shopId'])
            ->find();
        // 检索查询条件
        $filter   = [];
        $filter[] = ['shop_id', '=', $params['shopId']];

        if ($params['dataType'] == 'clerk') {

            $filter[] = ['clerk_id', '=', $clerk['clerk_id']];

        } else {
            if (in_array($clerk['role_id'], [2, 3])) {
                $filter[] = ['shop_id', '=', $clerk['shop_id']];
                $filter[] = ['clerk_id', '=', 0];
            } else {
                $filter[] = ['clerk_id', '=', $clerk['clerk_id']];
            }
        }

        $params['role'] > -1 && $filter[]         = ['role', '=', $param['role']];
        ! empty($params['searchKey']) && $filter[] = ['mobile', '=', $param['searchKey']];

        if ($params['status'] == 1) {
            //打盹
            $end_time   = time() - 86400 * 7;
            $start_time = time() - 86400 * 15;
            $filter[]   = ['update_time', '>', $start_time];
            $filter[]   = ['update_time', '<=', $end_time];
        }
        if ($params['status'] == 2) {
            //浅睡
            $end_time   = time() - 86400 * 15;
            $start_time = time() - 86400 * 30;
            $filter[]   = ['update_time', '>', $start_time];
            $filter[]   = ['update_time', '<=', $end_time];
        }
        if ($params['status'] == 3) {
            //沉睡
            $end_time = time() - 86400 * 30;

            $filter[] = ['update_time', '<=', $end_time];
        }

        // 获取列表数据

        $list = $this

            ->where($filter)

            ->where('is_delete', '=', 0)
            ->where('mobile', '<>', '')
            ->order(['times' => 'desc'])
            ->paginate($limit);

        // foreach ($list as $key => $item) {

        //     $list[$key]['times'] = Db::name('ding_order')->where($where)
        //         ->where('mobile', $item['mobile'])->count();

        // }
        return $list;
    }

    /**
     * 新增
     * @param array $data
     * @return mixed
     * @throws BaseException
     */
    public function add(array $data)
    {

        return $this->transaction(function () use ($data) {
            $member = Db::name('ding_clerk_member')
                ->where('shop_id', $data['shop_id'])

                ->where('mobile', $data['mobile'])->find();
            if ($member) {
                Db::name('ding_clerk_member')->where('id', $member['id'])
                    ->update(['is_delete' => 0,
                        'real_name'           => $data['real_name'],
                        'last_time'           => time(),
                        'update_time'         => time(),
                    ]);
            } else {
                if ($data['clerk_id'] > 0) {
                    Db::name('ding_clerk_member')->insert([
                        'real_name'   => $data['real_name'],
                        'mobile'      => $data['mobile'],
                        'shop_id'     => $data['shop_id'],
                        'clerk_id'    => 0,
                        'last_time'   => time(),
                        'create_time' => time(),
                        'store_id'    => self::$storeId,
                    ]);
                    $this->save([
                        'real_name' => $data['real_name'],
                        'mobile'    => $data['mobile'],
                        'shop_id'   => $data['shop_id'],
                        'clerk_id'  => $data['clerk_id'],
                        'last_time' => time(),
                        'store_id'  => self::$storeId,
                    ]);
                } else {
                    $this->save([
                        'real_name' => $data['real_name'],
                        'mobile'    => $data['mobile'],
                        'shop_id'   => $data['shop_id'],
                        'clerk_id'  => $data['clerk_id'],
                        'last_time' => time(),
                        'store_id'  => self::$storeId,
                    ]);
                }

            }

            return true;
        });
    }

    public function edit(array $data)
    {

        Db::name('ding_clerk_member')
            ->where('mobile', $this['mobile'])
            ->where('shop_id', $this['shop_id'])->update([
            'remark' => $data['remark'],
            'type'   => $data['type'],
            'month'  => $data['month'],
            'day'    => $data['day'],
            'role'   => $data['role'],

        ]);

        return true;

    }

}
